package org.lzfto.flink.demo.system.security.controller;

import org.lzfto.flink.demo.common.result.PubResult;
import org.lzfto.flink.demo.init.InitService;
import org.lzfto.flink.demo.system.security.entity.LoginData;
import org.lzfto.flink.demo.system.security.entity.SysUser;
import org.lzfto.flink.demo.system.security.service.SysUserService;
import org.lzfto.flink.demo.utils.SpringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/security/")
public class SecurityController {
	
	
	@Autowired
	private InitService initService;
	
	private SysUserService userService;
	
	
	@PostMapping("/account/login")
	public PubResult<String> login(@RequestBody LoginData loginData) {
		PubResult<String> regResult= initService.registerDatasource(loginData.getDesPassword());
		if (regResult.getFlag()==0) {
			return PubResult.error(regResult.getMessage());
		}
		
		if (userService==null) {
			userService=SpringUtils.getBean(SysUserService.class);
		}
		
		if (userService.getAllUsers()==null) {
			userService.init();
		}
		return userService.login(loginData);
	}
	
	@GetMapping("/account/logout")
	public PubResult<String> logout(String token) {
		if (userService==null) {
			userService=SpringUtils.getBean(SysUserService.class);
		};
		return userService.logout(token);
	}
	
	@PostMapping("/account/getUserInfo")
	public PubResult<Object> login(String token) {
		if (userService==null) {
			userService=SpringUtils.getBean(SysUserService.class);
		}
		SysUser user= userService.getUserByToken(token);
		if(user==null) {
			return PubResult.error("");
		}
		else {
			return PubResult.ok_data(user);
		}
	}

}
